package com.google.code.bankagregator.adapter.bank.alpha.parser;

import com.google.code.bankagregator.adapter.exception.AdapterConnectException;
import com.google.code.bankagregator.entities.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: kirill
 * Date: 11.06.13
 * Time: 23:03
 * To change this template use File | Settings | File Templates.
 */
public class FuncForDepParsers {
    private static final int INDEX_MIN_AMOUNT = 1;
    private static final int INDEX_FOR_REFILL = 2;
    private static final int INDEX_FOR_IDENTICAL_RATE = 9;
    public Document con = null;
    public Bank bank = null;

    public FuncForDepParsers(String url) throws AdapterConnectException {
        bank = new Bank();
        bank.setName("ПАО «Альфа-Банк» Украина");
        bank.setUrl("http://www.alfabank.com.ua/");
        try {
            con = Jsoup.connect(url).timeout(20000).get();
        } catch (IOException e) {
            throw new AdapterConnectException(e.getMessage());
        }
    }

    /**
     * Get list of terms
     *
     * @param tableLinesWithTerm - lines which keep terms
     * @return list of terms
     */
    public List<String> getTermList(Integer[] tableLinesWithTerm) {
        List<String> months = new ArrayList<>();
        Element monthsEl = null;
        for (int line : tableLinesWithTerm) {
            monthsEl = con.select("table.data tr").get(line).select("td:not([class=top])").first();
            String term = monthsEl.text().replaceAll("[^0-9.]+", "");
            if (!term.equals("")) {
                months.add(term);
            }

        }
        return months;
    }

    /**
     * Get min amount
     *
     * @return minAmount
     */
    public String getMinAmount() {
        Elements params = con.select("div#content p");
        Element elWithAmount = params.get(INDEX_MIN_AMOUNT);
        return elWithAmount.text();
    }

    /**
     * Get some deposit`s params
     *
     * @param minAmount
     * @param rowBegin           - the first row which keeps rate
     * @param currency
     * @param tableLinesWithTerm - lines which keep terms
     * @return some deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> parser(int minAmount, int rowBegin, Currency currency, Integer[] tableLinesWithTerm, String url) throws AdapterConnectException {
        List<Deposit> depositParam = new ArrayList<>();
        List<String> months = getTermList(tableLinesWithTerm);
        Elements params = con.select("div#content p");
        Element refill = params.get(INDEX_FOR_REFILL);
        Element name = con.select("h1").first();
        Element depositsElement = null;
        int i = 0;
        for (int line : tableLinesWithTerm) {
            Deposit deposit = new Deposit();
            depositsElement = con.select("table.data tr").get(line).select("td:not([class=top])").get(rowBegin);
            String depRate = depositsElement.text().replace("\u00a0", "");
            if (depRate.equals("-")) {
                depositsElement = con.select("table.data tr").get(INDEX_FOR_IDENTICAL_RATE).select("td:not([class=top])").get(rowBegin);
                depRate = depositsElement.text().replace("\u00a0", "");
                depRate = depRate.replace(",", ".").replace("%", "").replace("-", "-1.0");

            } else {
                depRate = depRate.replace(",", ".").replace("%", "").trim();
            }
            deposit.setDepositRate(Double.parseDouble(depRate));
            deposit.setTerm(Integer.parseInt(months.get(i)) * 31);
            i++;

            if (refill.text().substring(19, 33).equals("не допускается")) {
                deposit.setRefill(false);
            } else {
                deposit.setRefill(true);
            }
            deposit.setType(DepositType.Deposit);
            deposit.setCurrency(currency);
            deposit.setName(name.text());
            deposit.setBank(bank);
            deposit.setMinAmount(minAmount);
            deposit.setUrl(url);
            deposit.setState(State.ACTIVE);
            depositParam.add(deposit);
        }
        return depositParam;
    }
}
